<template>
  <div class="app-container">
    <el-row :gutter="15" class="mb8">
      <el-col :span="1.5">
        <el-button plain size="mini" icon="el-icon-plus" @click="handelAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain size="mini" :disabled="single" icon="el-icon-edit" @click="handelEdit">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain size="mini" :disabled="multiple" icon="el-icon-delete" @click="handelDel">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain size="mini" icon="el-icon-download" @click="handleExport">导出</el-button>
      </el-col>

      <el-form :model="queryData" ref="queryDataRef" :inline="true" class="el-form-search">
        <!--input输入-->
        <el-form-item label="电话号码" prop="phone" class="el-form-search-item">
          <el-input clearable placeholder="输入电话号码" v-model.trim="queryData.phone"></el-input>
        </el-form-item>
        <el-form-item class="el-form-search-item">
          <el-button type="primary" size="mini" icon="el-icon-search" @click="querySearch">搜索</el-button>
          <el-button size="mini" icon="el-icon-refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <el-table :height="tableHeight" border :data="simCardList" v-loading="loading"
      @selection-change="handelSelectionChange" stripe style="width: 100%">
      <!-- <el-table-column type="selection" width="50" align="center"></el-table-column> -->
      <el-table-column label="排序" prop="sort" width="50" align="center"></el-table-column>
      <el-table-column label="电话号码" prop="phone" width="120" align="center"></el-table-column>
      <el-table-column label="ICCId" prop="iccId" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column label="无线SN码" prop="sn" width="120" align="center"></el-table-column>
      <el-table-column label="无线IMEI" prop="imei" width="130" align="center"></el-table-column>
      <!-- <el-table-column
        label="合约期"
        prop="contractPeriod"
        width="120"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.contractPeriod }} 月/期
        </template>
</el-table-column> -->
      <el-table-column label="合约套餐" prop="contractPackage" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column label="开卡日期" prop="cardOpenDate" width="100" align="center"></el-table-column>
      <el-table-column label="截止日期" prop="expirationDate" width="100" align="center"></el-table-column>
      <el-table-column label="预警日期" prop="alertDate" width="100" align="center"></el-table-column>

      <el-table-column label="当前预警" prop="endDateBillingPeriod" width="100" align="center"></el-table-column>

      <el-table-column label="操作" align="center" width="120">
        <template slot-scope="scope">
          <el-button type="text" size="mini" icon="el-icon-edit" @click="handelEdit(scope.row)">修改</el-button>
          <el-button type="text" size="mini" icon="el-icon-delete" @click="handelDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryData.pageNum" :limit.sync="queryData.pageSize"
      @pagination="getList" />

    <el-dialog :title="title" :visible.sync="open" v-dialogDrag width="800px" :close-on-click-modal="false">
      <el-form :model="formData" :rules="rules" ref="formDataRef" label-width="100px" @submit.prevent
        label-position="left">
        <!-- 第一行 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <!--电话号码-->
            <el-form-item label="电话号码" prop="phone">
              <el-input clearable placeholder="输入电话号码" v-model="formData.phone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--ICCId-->
            <el-form-item label="ICCID" prop="iccId">
              <el-input clearable placeholder="输入ICCID" v-model="formData.iccId"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第三行 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <!--无线SN码-->
            <el-form-item label="无线SN码" prop="sn">
              <el-input clearable placeholder="输入无线SN码" v-model="formData.sn"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--无线IMEI-->
            <el-form-item label="无线IMEI" prop="imei">
              <el-input clearable placeholder="输入无线IMEI" v-model="formData.imei"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第四行 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <!--合约期-->
            <el-form-item label="合约期" prop="contractPeriod">
              <el-input clearable placeholder="输入合约期" v-model.trim="formData.contractPeriod"
                @change="handleCardOpenDateChange"><template slot="append">月/期</template></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--合约套餐-->

            <el-form-item label="合约套餐" prop="contractPackage">
              <el-input clearable placeholder="输入合约套餐" type="textarea" :rows="1" :maxlength="64" resize="none"
                show-word-limit v-model.trim="formData.contractPackage"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第五行 -->
        <el-row :gutter="15">

        </el-row>
        <!-- 第六行 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <!--开卡日期-->
            <el-form-item label="开卡日期" prop="cardOpenDate">
              <el-date-picker v-model="formData.cardOpenDate" type="date" placeholder="选择开卡日期"
                @change="handleCardOpenDateChange" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--截止日期-->
            <el-form-item label="截止日期" prop="expirationDate">
              <el-date-picker v-model="formData.expirationDate" type="date" placeholder="输入截止日期" :disabled="true"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第七行 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <!--预警日期-->
            <el-form-item label="预警日期" prop="alertDate">
              <el-date-picker v-model="formData.alertDate" type="date" placeholder="选择预警日期" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--当前预警-->
            <el-form-item label="当前预警" prop="endDateBillingPeriod">
              <el-date-picker v-model="formData.endDateBillingPeriod" type="date" placeholder="当前预警"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="sim排序" prop="sort">
              <el-input v-model="formData.sort" placeholder="请输入排序" clearable></el-input>
              <!-- <el-autocomplete v-model="formData.sort" :fetch-suggestions="querySearchSort" @select="handleSelect"
                placeholder="请输入排序" :trigger-on-focus="true" class="from-select">
                <template #default="{ item }">
                  <div class="autocomplete-item-disabled">{{ item.value }}</div>
                </template>
              </el-autocomplete> -->
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormData">提交</el-button>
        <el-button @click="close">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSimCard,
  addSimCard,
  getByNum,
  editSimCard,
  removeSimCard,
  getSimSortList
} from "@/api/maintenance/simCard";

export default {
  data() {
    return {
      loading: false,
      excursionDay: 0,//偏移天数

      /**搜索栏 */
      queryData: {
        pageNum: 1,
        pageSize: 30,
        phone: undefined,
        orderBy: "update_time",
        isAsc: "asc",
      },

      /**表格数据 */
      tableHeight: "calc(100vh - 200px)",
      simCardList: [],
      single: true,
      multiple: true,
      total: 0,
      ids: [],

      /**新增/修改对话框 */
      title: "",
      open: false,
      formData: {
        cardOpenDate: '', // 开始日期
        contractPeriod: 36, // 合约期（月数）
        expirationDate: '', // 结束日期
        alertDate: '',
        endDateBillingPeriod: '',
        sort: ''
      },
      rules: {
        phone: [
          { required: true, message: "电话号码不能为空", trigger: "blur" },
          // {
          //   pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
          //   message: "请输入正确的手机号码",
          //   trigger: "blur",
          // },
        ],
        iccId: [
          { required: true, message: "ICCId不能为空", trigger: "blur" },
          { mini: 99, max: 99, message: "ICCI最大不能超过30位", trigger: "blur" },
        ],
        sn: [
          { required: true, message: "无线SN码不能为空", trigger: "blur" },
          { mini: 99, max: 99, message: "无线SN码的位数是32", trigger: "blur" },
        ],
        imei: [
          { required: true, message: "无线IMEL不能为空", trigger: "blur" },
          { mini: 99, max: 99, message: "无线IMEL的位数是32", trigger: "blur" },
        ],
        monthlyFlow: [
          { required: true, message: "月流量不能为空", trigger: "blur" },
          {
            validator: this.formValidation.validateNumber,
            message: "只能输入数字",
            trigger: "blur",
          },
        ],
        sort: [
          {
            validator: this.validateSortExistence,
            trigger: "blur",
          }
        ],
        sortList: []
      },
    };
  },
  created() {
    this.getList();
    getSimSortList().then(response => {
      const existingData = response.data.map(item => String(item.sort))
      this.sortList = existingData
    })
  },
  methods: {
    /**获取sim卡列表 */
    getList() {
      this.loading = true;
      listSimCard(this.queryData).then((response) => {
        this.simCardList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /**重置表单 */
    reset() {
      this.resetForm("formDataRef");
    },
    /**新增sim卡 */
    handelAdd() {
      this.reset();
      this.formData.cardOpenDate = ''; // Start date
      this.formData.contractPeriod = 36; // Contract period (in months)
      this.formData.expirationDate = ''; // End date
      this.formData.alertDate = '';
      this.formData.endDateBillingPeriod = '';
      this.open = true;
      this.title = "新增SIM卡信息";
      this.formData.sort = Number(this.sortList[this.sortList.length - 1]) + 1
    },
    /**修改sim卡 */
    handelEdit(row) {
      this.reset();
      this.open = true;
      this.title = "修改SIM卡信息";

      const num = row.num || this.ids[0];
      getByNum(num).then((response) => {
        this.formData = response.data;
      });
    },
    /**删除sim卡 */
    handelDel(row) {
      const ids = row.num || this.ids;
      this.$modal
        .confirm("确认删除吗？")
        .then(function () {
          removeSimCard(ids);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .catch(() => { });
    },
    /**搜索按钮 */
    querySearch() {
      this.getList();
      this.queryData.pageNum = 1;
    },
    /**重置 */
    resetSearch() {
      this.resetForm("queryDataRef");
      this.querySearch();
    },
    /**多选 */
    handelSelectionChange(val) {
      this.ids = val.map((item) => item.num);
      this.single = this.ids.length != 1;
      this.multiple = !this.ids.length;
    },
    /**提交 */
    submitFormData() {
      this.$refs["formDataRef"].validate((valid) => {
        if (valid) {
          if (this.formData.num != undefined) {
            //修改
            editSimCard(this.formData).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.getList();
              this.open = false;
            });
          } else {
            //新增
            console.log(this.formData)
            addSimCard(this.formData).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.getList();
              this.open = false;
            });
          }
        }
      });
    },
    /**取消 */
    close() {
      this.resetForm("formDataRef");
      this.open = false;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "zk/simCard/export", //后端接口
        {
          ...this.queryData, // 参数
        },
        `sim卡信息_${new Date().getTime()}.xlsx` //导出的文件名称
      );
    },
    /** 选择开卡日期的时候+合约期=截止日期 */
    handleCardOpenDateChange() {

      if (!this.formData.cardOpenDate || !this.formData.contractPeriod) {
        this.formData.expirationDate = '';
        return;
      }

      // 将开始日期转换为 Date 对象
      const startDate = new Date(this.formData.cardOpenDate);

      // 计算结束日期
      const endDate = new Date(startDate);
      endDate.setMonth(startDate.getMonth() + parseInt(this.formData.contractPeriod));

      // 获取系统的偏移日期，设置预警日期
      this.getConfigKey("sys:sim:excursionDay").then((response) => {

        this.excursionDay = response.msg;

        // 计算预警日期
        const alertDate = new Date(endDate)
        alertDate.setDate(alertDate.getDate() + parseInt(this.excursionDay));

        this.formData.alertDate = alertDate

      })

      // 设置截至日期
      this.formData.expirationDate = endDate;

    },
    // 模拟搜索建议（返回不可选的建议项）
    querySearchSort(queryString, cb) {
      getSimSortList().then(response => {
        const existingData = response.data.map(item => String(item.sort))

        const results = existingData
          .map(item => ({
            value: item + `已存在`,
            disabled: true // 标记为不可选（逻辑层标记）
          }));
        cb(results);
      })
    },
    // 阻止选中行为
    handleSelect(item) {
      if (item.disabled) {
        this.$modal.msgError("不可选择已有项，请手动输入！")
        this.deviceFormData.sort = ''; // 清空输入（或恢复原值）
        return false; // 阻止默认选中
      }
    },
    // 校验排序是否存在的方法
    validateSortExistence: (rule, value, callback) => {
      // if (!value) {
      //   callback(new Error('请输入排序值'));
      //   return;
      // }
      getSimSortList().then(response => {
        const existingData = response.data.map(item => String(item.sort))

        if (existingData.includes(value)) {
          callback(new Error('该排序值已存在，请重新输入！'));
        } else {
          callback(); // 校验通过
        }
      })

    }
  },
};
</script>

<style lang="scss" scoped>
.autocomplete-item-disabled {
  color: #999;
  cursor: not-allowed;
  pointer-events: none;
  /* 禁止点击 */
}
</style>
